<?php
/*
* This class provides methods to realize a company
*
* @author Open Dynamics <info@o-dyn.de>
* @name company
* @version 0.4
* @package Collabtive
* @link http://www.o-dyn.de
* @license http://opensource.org/licenses/gpl-license.php GNU General Public License v3 or later
*/

class company
{
    /*
    * Constructor
    * Initialize the event log
    */
    function company()
    {
    }

    /*
    * Add a new company
    *
    * @param string $name Name of the company
    * @param string $email Email-address
    * @param string $phone Phonenumber
    * @param string $address1 Main address
    * @param string $address2 Second address
    * @param string $state State
    * @param string $country Country
    * @param string $logo Company's logo
    * @return bool
    */
    function add($name, $email, $phone, $address1, $address2, $state, $country, $logo, $user_id = NULL, $parent_id = NULL) {
        
    	if ( !$user_id )
    		$user_id = $_SESSION['userid'];
    	
    	$name = mysql_real_escape_string($name);
        $email = mysql_real_escape_string($email);
        $phone = mysql_real_escape_string($phone);
        $address1 = mysql_real_escape_string($address1);
        $address2 = mysql_real_escape_string($address2);
        $state = mysql_real_escape_string($state);
        $country = mysql_real_escape_string($country);
        $logo = mysql_real_escape_string($logo);
        $user_id = mysql_real_escape_string($user_id);
        $parent_id = mysql_real_escape_string($parent_id);
        
        $query = "INSERT INTO company (ID, name, email, phone, address1, address2, state, country, logo, user_creator_id, parent_id) 
        	VALUES ('', '$name', '$email', '$phone', '$address1', '$address2', '$state', '$country', '$logo', '$user_id', '$parent_id');";
        
        $result = mysql_query($query);
        
        if ( $result ) {
            //$this->mylog->add('company' , 1);
            return mysql_insert_id();
        } else return false;
        
    }

    /*
    * Edit a company
    *
    * @param int $id Company ID
    * @param string $name Company's name
    * @param string $email Emal address
    * @param string $address1 Main address
    * @param string $address2 Second address
    * @param string $state State
    * @param string $country Country
    * @param string $logo Company's logo
    * @return bool
    */
    function edit($id, $name, $email, $phone, $address1, $address2, $state, $country, $logo, $parent_id)
    {
        $id = (int) $id;
        $name = mysql_real_escape_string($name);
        $email = mysql_real_escape_string($email);
        $phone = mysql_real_escape_string($phone);
        $address1 = mysql_real_escape_string($address1);
        $address2 = mysql_real_escape_string($address2);
        $state = mysql_real_escape_string($state);
        $country = mysql_real_escape_string($country);
        $logo = mysql_real_escape_string($logo);
        $parent_id = (int) mysql_real_escape_string($parent_id);
        
        $query = "UPDATE company SET name='$name', email='$email', phone='$phone', address1='$address1', address2='$address2', state='$state', country='$country', logo='$logo', parent_id = '$parent_id' WHERE ID = $id;";
        
        $upd = mysql_query($query);
        
        if ($upd)
        {
            //$this->mylog->add('company' , 2);
            return true;
        }
        else
        {
            return false;
        }
    }

    /*
    * Delete a company
    *
    * @param int $id Company ID
    * @return bool
    */
    function del($id) {
    	
        $id = (int) mysql_real_escape_string($id);
        
        $query = "DELETE FROM company WHERE ID = $id;";
        $result = mysql_query($query);
        
        if ( $result ) {
        	
        	$query = "DELETE FROM company WHERE parent_id = $id;";
        	$result_subquery = mysql_query($query);
        	
        	if ( $result && $result_subquery ) return TRUE;
        	
        } else return FALSE;
        
    }

	/*
    * Assign a user to a company
    *
    * @param int company Company ID
    * @param int user User ID
    * @param int $id Company ID
    * @return bool
    */
	function assign($company, $user) {
		
		$company = (int) $company;
		$user = (int) $user;
		
		// User already exists
		$query = ( $this->userExists($user) ) 
			? "UPDATE company_assigned SET company = $company WHERE user = $user;"
			: "INSERT INTO company_assigned (ID, user, company) VALUES ('', '$user', '$company');";
		
		$result = mysql_query($query);
		
		if( $result ) return true;
		else return false;
		
	}
	
	/**
	 * Check if the specified user is already related with a company in the data base
	 * @param int $user_id User ID
	 * @return bool
	 */
	public function userExists($user_id = NULL) {
		
		if ( !$user_id ) return false;
		
		// Verify user in assingns table
		$query = "SELECT COUNT(ID) AS count FROM company_assigned WHERE user = $user_id;";		
		$result = mysql_query($query);
		$count = mysql_fetch_assoc($result);
		
		if ( (int)$count['count'] > 0 ) return true;
		else return false;
		
	}
	
	/*
    * Remove a user from a company
    *
    * @param int company Company ID
    * @param int user User ID
    * @param int $id Company ID
    * @return bool
    */
	function deassign($company, $user) {
		
		$company = (int) $company;
		$user = (int) $user;
		
		// Delete users data on association tabble
		$query = ( !$user ) 
			? "DELETE FROM company_assigned WHERE company = $company;" 
			: "DELETE FROM company_assigned WHERE company = $company AND user = $user;";
		
		$result = mysql_query($query);
		
		if ( $result ) return true;
		else return false;
		
	}
	
    /*
    * Return the profile of a company
    *
    * @param int $id Company ID
    * @return bool
    */
    function getProfile($id)
    {
        $id = (int) mysql_real_escape_string( $id );

        $sel = mysql_query("SELECT * FROM company WHERE ID = $id");
        $profile = mysql_fetch_assoc($sel);


        if (!empty($profile))
        {
            return $profile;
        }
        else
        {
            return false;
        }
    }
    
    public function getCompany($company_id = NULL) {
    	
    	if ( !$company_id ) return false;
    	
    	$company_id = (int) $company_id;
    	
    	$query = "SELECT * FROM company WHERE ID = $company_id LIMIT 0,1;";
    	$result = mysql_query($query);
    	$company_data = mysql_fetch_assoc($result);
    	
    	$company_data['address'] = $company_data['address1'] . ', ' . $company_data['address2'];
    	
    	if ( !empty( $company_data ) ) {
    		
    		// Get company members
    		$company_members = $this->getCompanyMembers($company_id);
    		$members = $company_members['staff'];
    		
    		// Add to main array
    		$company_data['members'] = $members;
    		
    		return $company_data;
    		
    	} else return false;
    	
    }
    
	function getAllCompanies()
	{
		$sel = mysql_query("SELECT * FROM company");
		$companies = array();
		
		while($company = mysql_fetch_array($sel))
		{
			array_push($companies,$company);
		}
		
		if(!empty($companies))
		{
			return $companies;
		}
		else
		{
			return false;
		}
	}
	
	public function getAllCompaniesAndMembers($members = true) {
		
		$query = "SELECT * FROM company;";
		$result = mysql_query($query);
		
		$companies = array();
		
		while ( $company = mysql_fetch_assoc($result) ) {
			$companies[] = $company;
		}
		
		// Memebers
		if ( $members ) {
			foreach ( $companies as $i => $company ) {
				
				$company_id = $company['ID'];
				
				$query = "SELECT user, company FROM company_assigned WHERE company = $company_id;";
				
				$result = mysql_query($query);
				
				$members = array();
				
				$user = new user();
				
				while ( $assoc = mysql_fetch_assoc($result) ) {
					$members[] = $user->getProfile( $assoc['user'] );
				}
				
				$companies[$i]['members'] = $members;
				
			}
			
		}
		
		return $companies;
		
	}
	
	function getUserCompany($user_id = null) {
		
		if ( !$user_id ) return array();
		
		$query = "SELECT c.* FROM company_assigned AS ca INNER JOIN company AS c ON ca.company = c.ID  WHERE ca.user = $user_id;";
		$result = mysql_query($query);
		
		$companies = array();
		
		while ( $company = mysql_fetch_assoc($result) ) {
			$companies[] = $company;
		}
		
		if ( empty($companies) ) return array(); 
		
		return $companies[0];
		
	}
	
    /*
    * Return all members of a company
    *
    * @param int $id Company ID
    * @return array $staff Members of the company
    */
    function getCompanyMembers($id)
    {
        $id = (int) $id;

        $sel = mysql_query("SELECT user,company FROM company_assigned WHERE company = $id");
        $staff = array();
        $userobj = (object) new user();
        $company = $this->getProfile($id);
        while($member = mysql_fetch_row($sel))
        {
            $user = $userobj->getProfile($member[0]);
            array_push($staff,$user); 
        }
        #SELECT user.*,company.* FROM user,company,company_assigned WHERE company_assigned.ID = company.ID AND company_assigned.user = user.company HAVING user.ID = 1
        $company["staff"] = $staff;

        if (!empty($company))
        {
            return $company;
        }
        else
        {
            return false;
        }
    }
    
    public function getAllCompaniesForHierarchy() {
    	
    	$companies = $this->getAllCompanies();
    	 
    	if ( empty($companies) ) return array();
    	 
    	$fields_for_hierarchy = array(
    			'ID', 'parent_id', 'name'
    	);
    	 
    	foreach ($companies as $i => $company) {
    		foreach ($company as $j => $value) {
    			if ( !in_array($j, $fields_for_hierarchy) ) {
    				unset($companies[$i][$j]);
    				unset($companies[$i][0]);
    			}
    		}
    	}
    	
    	return $companies;
    	
    }
    
    public function getHierarchy() {
    	
    	$companies = $this->getAllCompaniesForHierarchy();
    	
    	$hierarchy = $this->companiesToTree($companies);
    	    	
    	return $hierarchy;
    	
    }
    
    public function getHierarchyForSelect() {
    	
    	$companies = $this->getHierarchy();
    	
    	$companies_hierarchy = explode( PHP_EOL, $this->toUL($companies, 0) );
    	
    	$hierarchy_array = array();
    	
    	foreach ($companies_hierarchy as $i => $hierarchy) {
    		if ( !empty($hierarchy) ) {
    			$hierarchy_explode = explode('.', $hierarchy);
    			$hierarchy_array[$i]['ID'] = $hierarchy_explode[0];
    			$hierarchy_array[$i]['parent_id'] = $hierarchy_explode[1];
    			$hierarchy_array[$i]['hierarchy'] = $hierarchy_explode[2];
    		}
    	}
    	
    	return $hierarchy_array;
    	
    }
    
    public function getHierarchyForUl() {
    	
    	$companies = $this->getHierarchy();
    	
    	if ( empty($companies) ) return array();
    	
    	return $companies_hierarchy = $this->hierarchyUl($companies);
    	
    }
    
    public function companiesToTree(&$companies) {
    
    	$map = array(
    			0 => array( 'children' => array() )
    	);
    
    	foreach ( $companies as &$company ) {
    		$company['children'] = array();
    		$map[ $company['ID'] ] = &$company;
    	}
    
    	foreach ($companies as &$company) {
    		$map[$company['parent_id']]['children'][] = &$company;
    	}
    
    	return $map[0]['children'];
    
    }
    
    function toUL ($arr, $pass = 0) {
    
    	$html = '';
    
    	foreach ( $arr as $v ) {
    
    		//$html.= '<li>';
    		$html.= $v['ID'] . '.' . $v['parent_id'] . '.';
    		$html .= str_repeat("- - ", $pass); // use the $pass value to create the --
    		$html .= $v['name'] . PHP_EOL;
    
    		if ( array_key_exists('children', $v) ) {
    			$html.= $this->toUL($v['children'], $pass + 1);
    		}
    		
    	}
    	
    	//$html.= '</ul>' . PHP_EOL;
    
    	return $html;
    
    }
    
    function hierarchyUl($arr) {
    
    	$html = '<ul>' . PHP_EOL;
    
    	foreach ( $arr as $v ) {
    		
    		$html.= '<li>';
    		$html.= '<a href="managecompany.php?action=showcompany&company_id=' . $v['ID'] . '" class="company-link">' . $v['name'] . '</a>';
    		$html.= '<a href="managecompany.php?action=editform&company_id=' . $v['ID'] . '" class="options edit" title="Editar">E</a>';
    		$html.= '<a href="managecompany.php?action=del&company_id=' . $v['ID'] . '" class="options delete" title="Eliminar">X</a>';
    		$html.= '</li>' . PHP_EOL;
    		
    		if ( array_key_exists('children', $v) ) {
    			$html.= $this->hierarchyUl($v['children']);
    		}
    
    	}
    	 
    	$html.= '</ul>' . PHP_EOL;
    
    	return $html;
    
    }
    
    public function hasChildren($company_id = NULL) {
    	
    	if ( !$company_id ) return FALSE;
    	
    	$company_id = (int) mysql_real_escape_string($company_id);
    	
    	$query = "SELECT COUNT(*) as count FROM company WHERE parent_id = $company_id;";
    	$result = mysql_query($query);
    	
    	$count = mysql_fetch_assoc($result);
    	
    	if ( (int) $count['count'] > 0 ) return TRUE;
    	else return FALSE;
    	    	
    }
    
    public function getChildren($company_id = NULL) {
    	
    	if ( !$company_id ) return FALSE;
    	 
    	$company_id = (int) mysql_real_escape_string($company_id);
    	
    	$query = "SELECT * FROM company WHERE parent_id = $company_id;";
    	$result = mysql_query($query);
    	
    	$companies = array();
    	
    	while ( $company = mysql_fetch_assoc($result) ) {
    		$companies[] = $company;
    	}
    	
    	if ( empty($companies) ) return array();
    	
    	return $companies;
    	
    }
    
}
